import json
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

# 验证码识别
import ddddocr

# 显示等待，更加智能
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 提供键盘按键的支持，比如：RETURN, F1, ALT等
from selenium.webdriver.common.keys import Keys

# from utils import is_login, load_cookies, save_cookies

driver = webdriver.Firefox()
# load_cookies(driver)


# def save_cookies():
#     driver.get("http://106.38.235.201:7080/portal/")
#     log_url()
#     driver.get("http://106.38.235.201:7080/portal/")
#     cookie_all = driver.get_cookies()
#     time.sleep(2)
#     print(cookie_all)
#     cookfile = open("./cookies.log", "w")
#     json.dump(cookie_all, cookfile)
#     cookfile.close()
#     return cookie_all


# def load_cookies():
#     if os.path.exists("cookies.log"):
#         print("开始加载cookie")
#         cookfile = open("cookies.log", "r")
#         cookie_all = json.load(cookfile)
#         cookfile.close()
#     else:
#         print("不存在cookie文件，登录并保存cookie")
#         cookie_all = save_cookies()
#     print("添加到驱动")
#     driver.get("http://106.38.235.201:7080/portal/")
#     for cookie in cookie_all:
#         driver.add_cookie(cookie)
#     driver.get("http://106.38.235.201:7080/portal/")
#     time.sleep(3)


# 判断是否已经登录
# if is_login(driver) is False:
def log_url():
    print("开始登录")
    driver.get("http://106.38.235.201:7080/cas/login")

    # 操作cookies
    # cookies = driver.get_cookies()
    # for cookie in cookies:
    #     driver.add_cookie(cookie)
    #     # 需要刷新页面，向服务器发送cookies
    #     driver.refresh()

    driver.find_element(By.ID, "username").send_keys("43132220201")
    driver.find_element(By.ID, "password").send_keys("Tmxczx@1234")

    # 获取验证码并保存
    imgCode = driver.find_element(By.ID, "jcaptcha")
    imgCode.screenshot("jcaptcha.jpg")
    # 验证码识别
    ocr = ddddocr.DdddOcr()
    with open("jcaptcha.jpg", "rb") as f:
        img_bytes = f.read()
        res = ocr.classification(img_bytes)
        print(res)
    driver.find_element(By.ID, "jcaptcha_response").send_keys(res)

    # 登录
    driver.find_element(By.ID, "loginBut").click()

    # 浏览器关闭之前保存cookies
    # save_cookies(driver)
    time.sleep(2)
    # driver.close()
    return driver.get_cookies()


# else:
#     try:
#         element = WebDriverWait(driver, 10).until(
#             EC.presence_of_element_located((By.NAME, "menuIcon1"))
#         )
#         if element:
#             print("我已经成功等待")
#         else:
#             print("失败是我")
#     finally:
#         driver.quit()
#     print(666)
load_cookies()
